<template>
	<!-- 评价弹窗 -->
	<view class="evaluate-modal" v-if="visible" @tap="handleMaskClick">
		<view class="modal-content" @tap.stop>
			<!-- 弹窗头部 -->
			<view class="modal-header">
				<text class="title">评价订单</text>
				<uni-icons type="close" size="24" color="#999" @click="close" />
			</view>

			<!-- 评分组件 -->
			<view class="rating-section">
				<text class="section-title">菜品评分</text>
				<view class="star-rating">
					<view v-for="i in 5" :key="i" class="star" :class="{ active: i <= currentRating }"
						@click="handleRate(i)">
						<uni-icons :type="i <= currentRating ? 'star-filled' : 'star'" size="32"
							:color="i <= currentRating ? '#ffd700' : '#ddd'" />
					</view>
				</view>
			</view>

			<!-- 评论输入 -->
			<view class="comment-section">
				<text class="section-title">菜品评价</text>
				<textarea v-model="comment" class="comment-input" placeholder="请写下对菜品的评价，其他小伙伴会参考你的评价哦～" maxlength="200"
					auto-height />
				<text class="word-count">{{ comment.length }}/200</text>
			</view>

			<!-- 图片上传 -->
			<view class="upload-section">
				<text class="section-title">上传照片（选填）</text>
				<view class="upload-list">
					<view v-for="(item, index) in tempFiles" :key="index" class="preview-item">
						<image :src="item" class="preview-image" mode="aspectFill" />
						<view class="delete-btn" @click="removeImage(index)">
							<uni-icons type="close" size="18" color="#fff" />
						</view>
					</view>
					<view v-if="tempFiles.length < 4" class="upload-btn" @click="handleChooseImage">
						<uni-icons type="plus" size="32" color="#ccc" />
					</view>
				</view>
			</view>

			<!-- 提交按钮 -->
			<button class="submit-btn" :class="{ disabled: !canSubmit }" :disabled="!canSubmit" @click="handleSubmit">
				{{ submitText }}
			</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue'
	import {
		reviewItem
	} from '../request/api.js'


	const props = defineProps({
		visible: Boolean,
		orderId: String,
		itemId: String
	})

	const emit = defineEmits(['update:visible', 'submit'])

	// 评分数据
	const currentRating = ref(0)
	// 评论内容
	const comment = ref('')
	// 临时图片文件
	const tempFiles = ref([])

	// 是否可提交
	const canSubmit = computed(() => {
		return currentRating.value > 0 && comment.value.trim().length >= 10
	})

	// 提交按钮文字
	const submitText = computed(() => {
		return canSubmit.value ? '提交评价' : '请完成评价（至少10字）'
	})

	// 处理评分
	const handleRate = (score) => {
		currentRating.value = score
	}

	// 选择图片
	const chooseImage = async () => {
		try {
			const res = await uni.chooseImage({
				count: 1 - tempFiles.value.length,
				sizeType: ['compressed'],
				sourceType: ['album']
			})
			tempFiles.value = [...tempFiles.value, ...res.tempFilePaths]
		} catch (err) {
			console.log('取消选择')
		}
	}

	const handleChooseImage = () => {
		uni.chooseImage({
			count: 1,
			success: (res) => {
				const tempFilePaths = res.tempFilePaths;
				uploadImage(tempFilePaths[0]);
			}
		});
	};

	const uploadImage = (filePath) => {
		const serverUrl = 'http://175.178.118.46:3000'
		uni.uploadFile({
			url: `${serverUrl}/upload`,
			filePath: filePath,
			name: 'image',
			success: (res) => {
				const data = JSON.parse(res.data);
				// imageUrl.value = data.imageUrl;
				// $emit('imageUploaded', data.imageUrl)
				tempFiles.value = [...tempFiles.value, data.imageUrl]
			},
			fail: (err) => {
				console.error('上传失败:', err);
			}
		});
	};

	// 删除图片
	const removeImage = (index) => {
		tempFiles.value.splice(index, 1)
	}

	// 提交评价
	const handleSubmit = async () => {
		if (!canSubmit.value) return

		const formData = {
			orderId: props.orderId,
			rating: currentRating.value,
			comment: comment.value,
			imageUrl: tempFiles.value[0],
			itemId: props.itemId
		}

		try {
			// 这里调用提交接口
			await reviewItem(formData)
			uni.showToast({
				title: '评价成功',
				icon: 'success'
			})
			close()
			emit('submit', formData)
		} catch (err) {
			uni.showToast({
				title: '提交失败，请重试',
				icon: 'none'
			})
		}
	}

	// 关闭弹窗
	const close = () => {
		emit('update:visible', false)
	}

	// 点击遮罩层
	const handleMaskClick = () => {
		if (comment.value || currentRating.value > 0) {
			uni.showModal({
				title: '提示',
				content: '确定放弃当前编辑的内容吗？',
				success: (res) => {
					if (res.confirm) close()
				}
			})
		} else {
			close()
		}
	}
</script>

<style scoped>
	/* 弹窗容器 */
	.evaluate-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
	}

	/* 内容区域 */
	.modal-content {
		background: #fff;
		width: 85vw;
		max-width: 500px;
		border-radius: 12px;
		padding: 24px;
		max-height: 80vh;
		overflow-y: auto;
	}

	/* 头部样式 */
	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
	}

	.title {
		font-size: 18px;
		font-weight: 600;
		color: #333;
	}

	/* 评分区域 */
	.star-rating {
		display: flex;
		gap: 8px;
		margin: 12px 0;
	}

	.star {
		transition: transform 0.2s ease;
	}

	.star:active {
		transform: scale(1.1);
	}

	/* 评论输入 */
	.comment-section {
		margin: 16px 0;
	}

	.comment-input {
		width: 100%;
		min-height: 100px;
		padding: 12px;
		border: 1px solid #eee;
		border-radius: 8px;
		font-size: 14px;
		margin: 8px 0;
	}

	.word-count {
		display: block;
		text-align: right;
		font-size: 12px;
		color: #999;
	}

	/* 图片上传 */
	.upload-list {
		display: flex;
		flex-wrap: wrap;
		gap: 8px;
		margin-top: 12px;
	}

	.preview-item {
		width: 72px;
		height: 72px;
		border-radius: 8px;
		position: relative;
		overflow: hidden;
	}

	.preview-image {
		width: 100%;
		height: 100%;
	}

	.delete-btn {
		position: absolute;
		right: 4px;
		top: 4px;
		width: 20px;
		height: 20px;
		background: rgba(0, 0, 0, 0.6);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.upload-btn {
		width: 72px;
		height: 72px;
		border: 1px dashed #ddd;
		border-radius: 8px;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #f8f8f8;
	}

	/* 提交按钮 */
	.submit-btn {
		margin-top: 24px;
		background: #007aff;
		color: #fff;
		border-radius: 25px;
		height: 48px;
		font-size: 16px;
		transition: opacity 0.3s;
	}

	.submit-btn.disabled {
		background: #ccc;
		opacity: 0.7;
	}

	/* 部分标题样式 */
	.section-title {
		display: block;
		font-size: 14px;
		color: #666;
		margin-bottom: 8px;
	}
</style>